package com.yuelao.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Description
 *
 * @author fengliye
 * @version v1.0
 * @date 26/12/2018 16:14
 * @modify detail
 * 版本       修改人        修改时间      修改内容描述
 * ---------------------------------------------
 * <p>
 * ---------------------------------------------
 */
public class ZooKeeperConn {
    // declare zookeeper instance to access ZooKeeper ensemble
    private ZooKeeper zoo;
    final CountDownLatch connectedSignal = new CountDownLatch(1);

    // Method to connect zookeeper ensemble.
    public ZooKeeper connect(String host) throws IOException, InterruptedException {

        zoo = new ZooKeeper(host, 5000, (we) -> {
            if (we.getState() == Watcher.Event.KeeperState.SyncConnected) {
                System.out.println("success");
                connectedSignal.countDown();
            }
        }
        );

        connectedSignal.await();
        return zoo;
    }

    // Method to disconnect from zookeeper server
    public void close() throws InterruptedException {
        zoo.close();
    }

}
